<?php

namespace App\Http\Controllers\Account;


use App\Rules\AccountRule;
use App\Services\UserService;
use Auth;
use Illuminate\Http\Request;


class LoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        //控制器中使用中间件
        $this->middleware('guest')->except('logout'); //必须来宾使用,除了logout方法
        $this->middleware('auth')->only('logout'); //使用logout退出方法，必须是登录状态。

    }
    public function index()
    {
        //
        return view('account.login');
    }

    public function store(Request $request, UserService $userService)
    {

        $request->validate([
            'account' => ['required', $this->validateAccountField()],
            'password' => ['required', 'min:3'],
            'captcha' => ['required', 'captcha']
        ], ['captcha.captcha' => '验证码错误']);
//记住我
        $isLogin = Auth::attempt([$this->username() => $request->account, 'password' => $request->password],$request->remember);
        // return back()->with('error','账号或密码不存在')


        if ($isLogin) {
            //intended重定向上次的请求

            if (!is_null(session('preUrl'))) {
                $url=session('preUrl');
                $request->session()->forget('preUrl');
                return redirect($url);
            }
            return redirect()->intended('/');
        } else {
            return back()->with('danger', '账号或密码错误');
        }
    }
    public function logout()
    {
        Auth::logout();
        return redirect('/');
    }
}
